package com.chaofan.kings_poster.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import com.chaofan.kings_poster.common.RestfulMessage;
import com.chaofan.kings_poster.model.Hero;
import com.chaofan.kings_poster.model.Skin;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by Chaofan at 2018-12-10 17:06
 * email:chaofan2685@qq.com
 **/
@Component
public class RootApis {

    @Value(value = "${game.skin.sDataType}")
    private String sDataType;

    @Value(value = "${game.skin.SearchKey}")
    private String SearchKey;

    @Value(value = "${game.skin.iTypeId}")
    private String iTypeId;

    @Value(value = "${game.skin.iActId}")
    private String iActId;

    @Value(value = "${game.skin.api}")
    private String api;

    @Value(value = "${game.hero.api}")
    private String herolistApi;

    @Value(value = "${download.size}")
    private String downloadSize;

    @Value(value = "${skin.downloadPash}")
    private String downloadPash;

    /***
     * 导出文件
     * @param response
     */
    public void exportZip(HttpServletResponse response, File zip){
        OutputStream out = null;
        try {
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(zip));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(getZipName(zip.getName()),"UTF-8"));
            response.setContentType("application/zip");
            response.addHeader("Content-Length", "" + zip.length());
            out = new BufferedOutputStream(response.getOutputStream());
            out.write(buffer);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            //为了节省储存空间，在流关闭后删除文件
            FileUtil.del(zip);
            if(out != null ){
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
    }


    /**
     * 请求王者荣耀接口
     * @param name
     * @return
     */
    public List<Skin> requestApi(String name){
        HashMap<String,Object> form = MapUtil.newHashMap();
        form.put("sDataType",sDataType);
        form.put("SearchKey",SearchKey);
        form.put("SearchValue",name);
        form.put("iTypeId",iTypeId);
        form.put("iActId",iActId);
        String result = HttpUtil.get(api,form);
        List<Skin> skins = JsonUtil.getListBean(result,Skin.class,"List");
        return skins;
    }


    /**
     * 获取英雄列表
     * @return
     */
    public List<Hero> requestApi() {
        String result = HttpUtil.get(herolistApi).replace("\uFEFF[","[");
        List<Hero> heroes = JsonUtil.getListBean(result,Hero.class);
        return heroes;
    }

    public String getDownloadPash(){
        return getRootPash()+"/skin/download";
    }

    public String getZipPash(){
        return getRootPash()+"/skin/zip";
    }

    public String getRootPash() {
        Class aClass = new Object(){
            public Class getClassByThis(){
                return this.getClass();
            }
        }.getClass();
        String path = new ApplicationHome(aClass).getSource().getParentFile().toString();
        return path;
    }

    public RestfulMessage buildResultData(Object data){
        RestfulMessage resultData = new RestfulMessage();
        resultData.setCode(8200);
        resultData.setMessage("Success");
        resultData.setData(data);
        return resultData;
    }

    public RestfulMessage buildErrorResultData(String msg){
        RestfulMessage resultData = new RestfulMessage();
        resultData.setCode(8500);
        resultData.setMessage(msg);
        return resultData;
    }

    public String getZipName(String name){
        return name.substring(name.indexOf(")")+1);
    }

    public List<String> downloadImgs(String name, String downloadSize){
        List<String> errorList = new ArrayList<>();
        List<Skin> list = requestApi(name);
        for (Skin skin : list){
            Map<String,String> map = skin.getsProdImgNo();
            for (Map.Entry<String,String> entry : map.entrySet()) {
                String skinName = skin.getName();
                try {
                    if (entry.getKey().startsWith(downloadSize)) {
                        File file = null;
                        if ("sProdImgNo_".equals(downloadSize)) {
                            file = FileUtil.file(downloadPash + "/" + name + "/" + skinName + "/" + entry.getKey() + ".jpg");
                        } else {
                            file = FileUtil.file(downloadPash + "/" + skinName + ".jpg");
                        }
                        if (file.exists()) {
                            FileUtil.del(file);
                        } else {
                            HttpUtil.downloadFile(entry.getValue(), file);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    errorList.add(skinName+"--"+entry.getValue());
                }
            }
        }
        return errorList;
    }
}
